package nancal.mp.mvc.admin

import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import nancal.mp.db.mongo.entity.sys.*
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import nbcp.base.db.IdName
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.base.utils.SpringUtil
import nbcp.mvc.sys.*
import nbcp.myoql.db.mongo.deleteById
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.queryById
import nbcp.myoql.db.mongo.updateWithEntity

import org.bson.Document
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

/**
 * Created by CodeGenerator at 2021-03-14 15:58:11
 */
@Api(description = "菜单", tags = arrayOf("AppMenu"))
@RestController
@RequestMapping("/sys/app-menu")
class AppMenuAutoController {

    @ApiOperation("列表")
    @PostMapping("/list-saved-app")
    fun listAppIds(
        request: HttpServletRequest
    ): ListResult<String> {
        SpringUtil.getBean<MongoTemplate>().db.listCollectionNames().filter { it.startsWith("appMenu-") }
            .map { it.substring("appMenu-".length) }
            .apply {
                return ListResult.of(this)
            }
    }


    @ApiOperation("列表")
    @PostMapping("/list")
    fun list(
        @Require token: String,
        @Require appCode: String,
        request: HttpServletRequest
    ): ListResult<Document> {
//        var myMenuCodes = iamClient.myAuths(token, appCode, false, ResourceTypeEnum.Menu);
//
//        var auths = myMenuCodes.data

        mor.sys.appMenu(appCode).query()
            .orderByAsc { it.sort }
            .toTreeJson({ it.id }, { it.parent.id }, "", "menus")
            .toList()
            .apply {
                return ListResult.of(this)
            }
    }

//    private fun sort_with(menus: MutableList<MenuDefine>) {
//        RecursionUtil.execute<MenuDefine>(menus, { it.menus }, { wbs, index ->
//            var it = wbs.last();
//            it.menus.sortBy { it.sort }
//            return@execute RecursionReturnEnum.Go
//        });
//    }

//    private fun filter_with_roles(menus: MutableList<MenuDefine>, myMenuCodes: List<String>) {
//
//
//        RecursionUtil.execute<MenuDefine>(menus, { it.menus }, { wbs, index ->
//            var it = wbs.last();
//            if (it.code.isEmpty()) {
//                return@execute RecursionReturnEnum.Go
//            }
//
//            if (myMenuCodes.contains(it.code) == false) {
//                return@execute RecursionReturnEnum.Remove
//            }
//
//            it.menus.sortBy { it.sort }
//            return@execute RecursionReturnEnum.Go
//        })
//    }

    @ApiOperation("详情")
    @PostMapping("/detail/{id}")
    fun detail(
        @Require appCode: String,
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<AppMenu> {
        mor.sys.appMenu(appCode).queryById(id)
            .toEntity()
            .apply {
                if (this == null) {
                    return ApiResult.error<AppMenu>("找不到数据")
                }

                return ApiResult.of(this)
            }
    }

    /**
     * 遍历所有根节点更新。
     */
    @ApiOperation("更新")
    @PostMapping("/save")
    fun save(
        @Require appCode: String,
        pid: String,
        @org.springframework.web.bind.annotation.RequestBody entity: AppMenu,
        request: HttpServletRequest
    ): ApiResult<String> {
        //鉴权
        var userId = request.UserId;
        var actionName = if (entity.id.HasValue) "更新" else "添加"

        var parent = IdName();

        if (pid.HasValue) {
            parent = mor.sys.appMenu(appCode).queryById(pid).toEntity(IdName::class.java)!!;
        }

        entity.parent = parent;
        mor.sys.appMenu(appCode)
            .updateWithEntity(entity)
            .execSave().apply {
                if (this == 0) {
                    return ApiResult.error("${actionName}失败")
                }
            }

        return ApiResult.of(entity.id)
    }

    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    fun delete(
        @Require appCode: String,
        @Require id: String
    ): JsonResult {
        mor.sys.appMenu(appCode).deleteById(id).exec()
            .apply {
                if (this == 0) {
                    return JsonResult.error("删除失败")
                }
            }

        return JsonResult();
    }
}


